﻿/*************************************************
	作者: Plane
	邮箱: 1785275942@qq.com
	日期: 2021/02/24 16:34
	功能: .net core 服务端session连接

    //=================*=================\\
           教学官网：www.qiqiker.com
           关注微信公众号: PlaneZhong
           关注微信服务号: qiqikertuts           
               ~~获取更多教学资讯~~
    \\=================*=================//
*************************************************/

using PENet;
using System;
using KCPExampleProtocal;

namespace KCPExampleServer {
    class ServerSession : KCPSession<NetMsg> {
        protected override void OnConnected() {
            KCPTool.ColorLog(KCPLogColor.Green, "Client Online,Sid:{0}", m_sid);
        }

        protected override void OnDisConnected() {
            KCPTool.Warn("Client Offline,Sid:{0}", m_sid);
        }

        protected override void OnReceiveMsg(NetMsg msg) {
            KCPTool.ColorLog(KCPLogColor.Magentna, "Sid:{0},RcvClient,CMD:{1} {2}", m_sid, msg.cmd.ToString(), msg.info);
            if(msg.cmd == CMD.NetPing) {
                if(msg.netPing.isOver) {
                    CloseSession();
                }
                else {
                    //收到ping请求，则重置检查计数，并回复ping消息到客户端
                    checkCounter = 0;
                    NetMsg pingMsg = new NetMsg {
                        cmd = CMD.NetPing,
                        netPing = new NetPing {
                            isOver = false
                        }
                    };
                    SendMsg(pingMsg);
                }
            }
        }

        private int checkCounter;
        DateTime checkTime = DateTime.UtcNow.AddSeconds(5);
        protected override void OnUpdate(DateTime now) {
            if(now > checkTime) {
                checkTime = now.AddSeconds(5);
                checkCounter++;
                if(checkCounter > 3) {
                    NetMsg pingMsg = new NetMsg {
                        cmd = CMD.NetPing,
                        netPing = new NetPing { isOver = true }
                    };
                    OnReceiveMsg(pingMsg);
                }
            }
        }
    }
}
